import { Dispatch, SetStateAction } from "react";

export const updateForm = <T extends Object>(
  e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>,
  setForm: Dispatch<SetStateAction<T>>
) => {
  if (!e.target.name.startsWith("[")) {
    setForm((val) => ({ ...val, [e.target.name]: e.target.value }));
    return;
  }

  setForm((form) => {
    const newObj = { ...form };
    let ref: { [key: string]: any } = newObj;
    const keys = e.target.name
      .slice(1, -1)
      .split("][")
      .map((val) => val.slice(1, -1));

    for (let i = 0; i < keys.length; ref = ref[keys[i]], i++)
      i === keys.length - 1 && (ref[keys[i]] = e.target.value);

    return newObj;
  });
};
